<template>
  <div>
    <public-modal
      width="880px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content" class="form-wrapper">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          class="form-table-style"
          autocomplete="off"
          layout="inline"
          labelAlign="left"
          :labelCol="{ style: 'width: 140px' }"
        >
          <a-row type="flex">
            <a-col flex="auto">
              <a-form-model-item label="人员类型" prop="helpPersonType" :colon="false">
                <a-select
                  v-model="form.helpPersonType"
                  ref="select"
                  show-search
                  :disabled="actionType == 'edit'"
                  placeholder="请选择"
                  class="select-jurisdiction"
                >
                  <a-select-option :value="item.value" v-for="(item, index) in helpTypeList" :key="index">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col flex="410px">
              <a-form-model-item v-if="form.helpPersonType == 1" label="请选择民警" :colon="false">
                <a-select
                  show-search
                  allowClear
                  :disabled="actionType == 'edit'"
                  :value="value"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  v-model="form.helpPersonId"
                  ref="select"
                  placeholder="请输入民警姓名，两个字以上"
                  class="select-jurisdiction"
                  @search="handleSearch"
                  @change="handleChange"
                >
                  <a-select-option :value="item.id" v-for="(item, index) in policeList" :key="item.id"
                    >{{ item.userName }}(警号：{{ item.policeUserNo }})</a-select-option
                  >
                </a-select>
              </a-form-model-item>
              <a-form-model-item v-else label="身份证号" prop="helpIdCard" :colon="false">
                <a-input
                  :disabled="actionType == 'edit'"
                  :maxLength="18"
                  autocomplete="off"
                  placeholder="请输入"
                  v-model="form.helpIdCard"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <template v-if="form.helpPersonType != 1">
            <a-row type="flex">
              <a-col flex="auto">
                <a-form-model-item label="人员姓名" prop="helpName" :colon="false">
                  <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.helpName" />
                </a-form-model-item>
              </a-col>
              <a-col flex="410px">
                <a-form-model-item label="联系电话" prop="helpPhone" :colon="false">
                  <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.helpPhone" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row type="flex">
              <a-col flex="auto">
                <a-form-model-item
                  :label="form.helpPersonType === '4' ? '所属单位' : '居住地址'"
                  prop="orgName"
                  :colon="false"
                >
                  <a-input :maxLength="30" autocomplete="off" placeholder="请输入" v-model="form.orgName" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </template>
        </a-form-model>
      </div>
    </public-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import { checkIDCard } from '@/utils/validate.js'
import publicModal from '@/components/publicModal'
import { putAction, postAction } from '@/api/manage'
import { isMobile } from '@/utils/validate'
import { getDictItemsFromCache, getPoliceByTwoCharacter } from '../../../../api/api'
import { debounce } from 'lodash-es'

export default {
  name: 'addPoliceModal',
  components: { publicModal },
  props: {
    idCode: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      title: '新增',
      record: {},
      status: 0,
      publicVisible: false,
      imageUrl: [],
      fileList: [],
      showUploadList: { showPreviewIcon: false },
      form: {},
      rules: {
        helpPhone: [
          { required: true, message: '请输入手机号!' },
          {
            validator: (rule, value, callback) => {
              if (!isMobile(value)) {
                callback(new Error('请输入正确的手机号！'))
              } else {
                callback()
              }
            },
          },
        ],
        helpIdCard: [
          { required: true, message: '请输入!' },
          {
            validator: (rule, value, callback) => {
              if (!checkIDCard(value)) {
                callback(new Error('请输入正确的身份证号'))
              } else {
                callback()
              }
            },
          },
        ],
        orgName: [{ required: true, message: '请输入!' }],
      },
      actionType: 'add',
      helpTypeList: getDictItemsFromCache('wb_help_type'),
      policeList: [],
      value: undefined,
    }
  },
  mounted() {
    this.getPoliceByDebounce = debounce(this.getPolice.bind(this), 200)
  },
  methods: {
    async show(record, actionType = 'add') {
      this.record = record
      this.publicVisible = true
      this.actionType = actionType
      if (record && record.id) {
        this.title = `编辑关怀人员`
        this.form = { ...record }
        if (record.userImage) {
          const obj = {
            uid: record.userImage,
            name: record.userImage,
            status: 'done',
            url: record.imgPrefix + record.userImage,
          }
          this.fileList.push(obj)
          this.imageUrl.push(record.userImage)
        }
      } else {
        this.title = `新增关怀人员`
      }
    },

    remove(file) {
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })

      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
    },
    async customRequest(info) {
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      if (this.status == 0) formData.append('type', 2)
      else if (this.status == 1) formData.append('type', 63)
      else if (this.status == 2) formData.append('type', 64)
      let res = await uploadFile(formData)
      if (res.code == 200) {
        this.imageUrl.push(res.result.halfPath)
      }
    },
    uploadChange({ file, fileList }) {
      file.status = 'done'
      this.fileList = fileList
    },

    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        let url = ''
        if (this.actionType === 'add') {
          url = '/wb/helpinfo/addHelpInfo'
        } else {
          url = '/wb/helpinfo/updateHelpInfo'
        }
        const method = this.actionType === 'add' ? postAction : postAction
        try {
          const res = await method(url, this.form)
          this.$message.success(res.message)
          this.$emit('refresh')
          this.cancel()
        } catch (error) {
          // 处理错误
          console.error('请求失败:', error)
          this.$message.error('请求失败，请稍后重试！')
        }
      })
    },

    cancel() {
      this.publicVisible = false
      this.fileList = []
      this.imageUrl = []
      this.form = {}
    },
    getPolice(value) {
      const params = {
        character: value,
      }
      getPoliceByTwoCharacter(params)
        .then((res) => {
          let policeList = res.result
          this.policeList = policeList
          console.log(this.policeList)
        })
        .catch(() => {
          this.policeList = []
        })
    },
    handleSearch(value) {
      value = value ? value.trim() : value
      if (!value || value.length < 2) {
        return
      }
      this.getPoliceByDebounce(value)
    },
    handleChange(value) {
      value = value ? value.trim() : value
      if (!value || value.length < 2) {
        return
      }
      this.value = value
      this.getPoliceByDebounce(value)
    },
  },
}
</script>

<style scoped lang="less">
.formStyle {
  padding: 0.2rem;
  /deep/.ant-col {
    height: unset;
  }
  .ant-form-inline .ant-form-item-with-help {
    margin-bottom: 5px;
  }
}
.form-wrapper {
  padding: 32px 25px 20px 25px;
  /deep/.avatar-uploader {
    height: 136px;
  }
  .form-table-style {
    /deep/.ant-form-item-label {
      background: #084dbe;
      border: 1px solid #0855cc;
      padding-left: 12px;
      height: 100%;

      > label {
        font-weight: 500;
        font-size: 14px;
        color: #8fbbff;
      }
    }
    /deep/.ant-form-explain {
      position: absolute;
      z-index: 10;
      bottom: -5px;
      left: 10px;
    }
    /deep/.ant-form-item-control-wrapper {
      flex: 1;
      height: 100%;
    }
    /deep/.ant-form-item {
      align-items: stretch;
      margin-right: 0;
      height: 46px;
      display: flex;
    }
    /deep/.ant-form-item-with-help {
      margin-right: 0;
      margin-bottom: 0;
    }
    /deep/.ant-form-item-control {
      height: 100%;
      .ant-form-item-children {
        height: 100%;
        display: block;
        .ant-input {
          height: 100%;
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #fff;
          &::placeholder {
            color: #6ea7ff;
          }
        }
        .ant-select {
          height: 100%;
          vertical-align: top;
        }
        .ant-select-selection {
          height: 100%;
          background: #0a49af;
          border: 0;
          border-radius: 0;
        }
        .ant-select-selection__rendered {
          height: 100%;
        }
        .ant-select-selection-selected-value {
          line-height: 42px;
          color: #fff;
        }
        .ant-select-selection__placeholder {
          color: #6ea7ff;
        }
        .ant-select-search__field {
          color: #fff;
        }
      }
    }
  }
}

.imageUpload {
  margin-bottom: 150px;
  /deep/.avatar-uploader {
    > .ant-upload {
      width: 150px;
      height: 176px;
      background: var(--theme-input-bg);
      border: 1px solid var(--theme-input-border);
    }
  }

  /deep/.ant-upload-select-picture-card {
    width: 150px;
    height: 176px;
  }

  /deep/ .ant-upload-list-item {
    width: 150px;
    height: 176px;
  }

  .imgText {
    color: #1163b8;
    font-weight: 500;
  }

  .pictIcon {
    margin-bottom: 10px;
    width: 42px;
    height: 38px;
  }
}
</style>
